package Day008_List_Collections_set.ZuoYe;

import java.util.HashSet;
import java.util.Objects;

public class Test3 {
    public static void main(String[] args) {
        //创建集合
        HashSet<Student> set = new HashSet<>();
        //创建对象
        Student stu1 = new Student("张三","男",20);
        Student stu2 = new Student("李四","女",21);
        Student stu3 = new Student("张三","男",20);

        set.add(stu1);
        set.add(stu2);
        set.add(stu3);

        for (Student s : set) {
            System.out.println(s);  //Student{name='李四', sex='女', age=21}
                                    //Student{name='张三', sex='男', age=20}
                                    //Student{name='张三', sex='男', age=20}
        }

        /*重写equals() hashCode()方法后:     Student{name='张三', sex='男', age=20}
                                           Student{name='李四', sex='女', age=21}*/

    }
}

class Student{
    private String name;
    private String sex;
    private int age;

    public Student() {
    }

    public Student(String name, String sex, int age) {
        this.name = name;
        this.sex = sex;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", sex='" + sex + '\'' +
                ", age=" + age +
                '}';
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Student student = (Student) o;
        return age == student.age &&
                Objects.equals(name, student.name);
    }

    @Override
    public int hashCode() {

        return Objects.hash(name, age);
    }
}